//
//  AccountLoginInfo.swift
//  sss
//
//  Created by hrrMac on 2020/6/4.
//  Copyright © 2020 hrrMac. All rights reserved.
//

import Foundation

class LoginInfoTools {
    
    ///单例
    static let shareInstance = LoginInfoTools()
    
    var model: LoginModel
    
    public var token: String{
        get{
            return model.token
        }
    }
    
    private init(){
        self.model = Self.getLoginInfo()
    }
    
}

extension LoginInfoTools{
    
    ///获取登录信息
    private static func getLoginInfo() -> LoginModel{
        if let dicOC = NSDictionary(contentsOfFile: savePath()){
            let dic = dicOC as! Dictionary<String, Any>
            
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dic, options: [])
                let loginModel = try JSONDecoder().decode(LoginModel.self, from: jsonData)
                return loginModel
            } catch{
                let model = LoginModel()
                model.token = ""
                model.id = 0
                return model
            }
        }else{
            let model = LoginModel()
            model.token = ""
            model.id = 0
            return model
        }
    }
    
    ///保存登录信息
    static func saveLoginInfo(){
        let model = loginModelInfo
        do {
            let data: Data = try JSONEncoder().encode(model)
            let dic = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            let dicOC = dic as! NSDictionary
            let success = dicOC.write(toFile: savePath(), atomically: true)
            if success {
                print("写入成功")
            }else{
                print("写入失败")
            }
        } catch  {
            print("解码失败")
        }
    }
    
    private static func savePath() -> String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let filePath = path?.appending("/login_info.plist")
        return filePath!
    }
    
    
}

var loginModelInfo: LoginModel {
    get{
        LoginInfoTools.shareInstance.model
    }
    set (temp){
        LoginInfoTools.shareInstance.model = temp
        LoginInfoTools.saveLoginInfo()
    }
}


